package base.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 线程间的通信---使用synchronized
public class LockDemo2 {

    public static void main (String[] args) {
        Share share = new Share();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    share.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();



        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BB").start();
    }




}


// 资源类
class Share {
    private int num = 0;
    private final Lock lock = new ReentrantLock();
    public synchronized void add() throws InterruptedException {

        while (num!=0){
            this.wait();

        }
            num++;
            System.out.println(Thread.currentThread().getName()+"::"+num);

        this.notify();
    }
    public synchronized void decr() throws InterruptedException {
        while (num!=1){
            this.wait();
        }

            num--;
            System.out.println(Thread.currentThread().getName()+"::"+num);

        this.notify();
    }

}
